import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp = "";
    private int serverPort = 0;
    public UdpEchoClient(String ip, int port) throws SocketException {
        //客户端自动分配端口
        socket = new DatagramSocket();
        this.serverIp = ip;
        this.serverPort = port;
    }
    private void start() throws IOException {
        //客户端启动程序
        System.out.println("客户端启动！");
        //1.发送请求
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入您的请求：");
        String request = scanner.next();
        DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                InetAddress.getByName(this.serverIp), this.serverPort);
        socket.send(requestPacket);
        //2.等待服务器响应，解析响应数据
        DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
        socket.receive(responsePacket);
        String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
        //3.打印请求和响应
        System.out.printf("req=%s, resp=%s", request, response);
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9999);
        client.start();
    }
}
